package com.exartisan.thanhdoanhn;

import java.util.ArrayList;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.internal.widget.IcsAdapterView;
import com.actionbarsherlock.internal.widget.IcsAdapterView.OnItemSelectedListener;
import com.actionbarsherlock.internal.widget.IcsSpinner;
import com.exartisan.adapter.GalleryMenuDropDown;
import com.exartisan.adapter.ImagePagerAdapter;
import com.exartisan.adapter.VideoHolderPagerAdapter;
import com.exartisan.bean.GalleryContent;
import com.exartisan.customview.GalleryViewPager;
import com.exartisan.customview.smartgalleryimageview.ImageLoader;
import com.exartisan.network.NetworkUtility;
import com.exartisan.network.NewParamBuilder;
import com.exartisan.network.NewResponseTranslater;
import com.exartisan.network.NewRestConnector;
import com.exartisan.util.CommentDialog;
import com.exartisan.util.CommentDialog.onCommentListener;
import com.exartisan.util.FbUtil;
import com.exartisan.util.Util;
import com.facebook.Session;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class PhotoActivity extends Activity implements OnClickListener {

	private static final int INGALLERY = 0;
	private static final int INEVENT = 1;
	private GalleryViewPager contentView;
	private TextView tvImageDescription;
	private TextView tvLikes, tvComments;
	private ImagePagerAdapter imgAdapter;
	private ArrayList<GalleryContent> imgData;
	private ArrayList<GalleryContent> videoData;
	private TextView tvPage;
	private IcsSpinner spType;
	private GalleryMenuDropDown spAdapter;
	private VideoHolderPagerAdapter videoHolderAdapter;
	private static boolean isPhotoState = true;
	private ProgressDialog prDialog;
	private static boolean visible = false;
	private View controlsView;
	private View bar;
	private LinearLayout layoutLike;

	private HashMap<String, Integer> likeCount;
	private HashMap<String, Integer> commentCount;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photo);

		// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
		// getActionBar().hide();

		imgData = new ArrayList<GalleryContent>();
		videoData = new ArrayList<GalleryContent>();

		likeCount = new HashMap<String, Integer>();
		commentCount = new HashMap<String, Integer>();

		controlsView = findViewById(R.id.fullscreen_content_controls);
		contentView = (GalleryViewPager) findViewById(R.id.fullscreen_content);
		bar = findViewById(R.id.layout_bar);
		tvImageDescription = (TextView) findViewById(R.id.tvImageDescription);
		layoutLike = (LinearLayout) findViewById(R.id.layoutLike);
		tvLikes = (TextView) findViewById(R.id.tvLikesPhoto);
		tvComments = (TextView) findViewById(R.id.tvComments);

		tvPage = (TextView) findViewById(R.id.tvPage);

		spType = (IcsSpinner) findViewById(R.id.spType);
		spAdapter = new GalleryMenuDropDown(this);
		spType.setAdapter(spAdapter);

		contentView
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int pos) {
						if (isPhotoState) {
							tvLikes.setText("");
							tvComments.setText("");
							String id = imgData.get(pos).getFeedID();
							if (likeCount.containsKey(id)) {
								if (likeCount.get(id) != 0)
									tvLikes.setText(likeCount.get(id) + "");
							} else
								Util.setLikeCount(id, tvLikes, likeCount);
							if (commentCount.containsKey(id)) {
								if (commentCount.get(id) != 0)
									tvComments.setText(commentCount.get(id)
											+ "");
							} else
								Util.setCommentCount(id, tvComments,
										commentCount);
							tvImageDescription.setText(imgData.get(pos)
									.getTitle());
							tvPage.setText((pos + 1) + "/"
									+ imgAdapter.getCount());

							if (imgAdapter.isLiked(pos))
								layoutLike.setBackgroundColor(Color
										.parseColor("#a0bf0000"));
							else
								layoutLike.setBackgroundColor(Color
										.parseColor("#a0000000"));

						} else {
							tvImageDescription.setText(videoData.get(pos)
									.getTitle());
							tvPage.setText((pos + 1) + "/"
									+ videoHolderAdapter.getCount());
						}
						// contentView.setOnTouchListener(mOnTouchListener);
						super.onPageSelected(pos);
					}

				});

		spType.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(IcsAdapterView<?> parent, View view,
					int position, long id) {
				spAdapter.setSelectedPosition(position);
				Log.d("spinner", "" + spAdapter.isSelectedPhoto());
				if (spAdapter.isSelectedPhoto()) {
					isPhotoState = true;
					contentView.setAdapter(imgAdapter);
				} else {
					isPhotoState = false;
					contentView.setAdapter(videoHolderAdapter);
					if (videoData.size() < 1)
						tvPage.setText("");
					else
						tvPage.setText("1" + "/" + videoData.size());
				}
			}

			@Override
			public void onNothingSelected(IcsAdapterView<?> parent) {

			}
		});

		int type = getIntent().getExtras().getInt("type");
		getData(type);
	}

	private void showGallery(ArrayList<GalleryContent> content) {
		ArrayList<String> imgURLs = new ArrayList<String>();

		// videoData.add(new GalleryContent(1, "android.resource://" +
		// getPackageName()
		// + "/" + R.raw.big_buck_bunny, "Big buck bunny",
		// "def","http://static.kinokopilka.tv/system/images/screenshots/images/000/042/409/42409_original.jpg",
		// 2));

		for (GalleryContent c : content) {
			if (c.getType() == 1) {
				imgData.add(c);
				imgURLs.add(c.getResourceUrl());
			} else
				videoData.add(c);
			tvPage.setText("1" + "/" + imgData.size());
			tvImageDescription.setText(imgData.get(0).getTitle());
			String id = imgData.get(0).getFeedID();
			if (likeCount.containsKey(id)) {
				if (likeCount.get(id) != 0)
					tvLikes.setText(likeCount.get(id) + "");
			} else
				Util.setLikeCount(id, tvLikes, likeCount);
			if (commentCount.containsKey(id)) {
				if (commentCount.get(id) != 0)
					tvComments.setText(commentCount.get(id) + "");
			} else
				Util.setCommentCount(id, tvComments, commentCount);

			// setLikeCount(imgData.get(0).getFeedID(), tvLikes);
			// setCommentCount(imgData.get(0).getFeedID(), tvComments);
		}

		imgAdapter = new ImagePagerAdapter(this, imgURLs);
		videoHolderAdapter = new VideoHolderPagerAdapter(this, videoData);
		contentView.setAdapter(imgAdapter);
	}

	private void getData(final int type) {
		if (NetworkUtility.checkNetworkState(getApplicationContext())) {
			prDialog = ProgressDialog.show(getActivity(), "Tải dữ liệu",
					"Vui lòng chờ ...");

			RequestParams params = new RequestParams();
			if (type == INGALLERY){
				int id = getIntent().getExtras().getInt("id");
				params = NewParamBuilder.BuildParams(NewParamBuilder
						.BuildDetailAlbumData(id));
				}
			else if (type == INEVENT){
				long id = getIntent().getExtras().getLong("id");
				params = NewParamBuilder.BuildParams(NewParamBuilder
						.BuildEventGallery(id));
			}
			;

			NewRestConnector.post("", params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int arg0, String response) {
					// Log.d("Res", response);
					prDialog.dismiss();
					if (response == null) {
						Util.showToast("Không có dữ liệu", getActivity(),
								Toast.LENGTH_SHORT);
						finish();
						return;

					}
					Log.d("Res", response);
					super.onSuccess(arg0, response);
					if (NewResponseTranslater.checkSuccess(response)) {
						ArrayList<GalleryContent> content = new ArrayList<GalleryContent>();
						if (type == INGALLERY){
							content = NewResponseTranslater
									.getDetailGallery(response);
							int id = getIntent().getExtras().getInt("id");
							NewRestConnector.post("", NewParamBuilder.BuildParams(NewParamBuilder.BuildDetailMediaData(id)), new AsyncHttpResponseHandler());
						}
							
						else if (type == INEVENT)
							content = NewResponseTranslater
									.getEventGallery(response);
						showGallery(content);

					} else {
						Util.showToast("Không có dữ liệu", getActivity(),
								Toast.LENGTH_SHORT);
						finish();
					}

				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					prDialog.dismiss();
					super.onFailure(arg0, arg1);
					Util.showToast("Không thể kết nối đến server",
							getActivity(), Toast.LENGTH_SHORT);
					finish();
				}
			});
		} else {
			Util.showToast("Không có kết nối", getActivity(),
					Toast.LENGTH_SHORT);
			finish();
		}

	}

	private Activity getActivity() {
		return this;
	}

	public void onClickCommentPhoto(View view) {
		CommentDialog.show(getActivity(),
				imgData.get(contentView.getCurrentItem()).getFeedID(),
				new onCommentListener() {

					@Override
					public void onSuccess() {

						Util.setCommentCount(
								imgData.get(contentView.getCurrentItem())
										.getFeedID(), tvComments, commentCount);

					}
				});
	}

	public void onClickBack(View v) {
		finish();
	}

	public void onClickShare(View v) {
		FbUtil.shareToFb(getActivity(), "", "", "http://toiyeuhanoi.org.vn",
				imgData.get(contentView.getCurrentItem()).getResourceUrl());
	}

	public void onClickLikePhoto(View v) {
		final int currentPos = imgAdapter.getCurrentPosition();
		if (imgAdapter.isLiked(currentPos) == false) {
			FbUtil.likeId(imgData.get(currentPos).getFeedID(), getActivity(),
					new AsyncHttpResponseHandler() {

						@Override
						public void onSuccess(int arg0, String response) {
							super.onSuccess(arg0, response);
							layoutLike.setBackgroundColor(Color
									.parseColor("#a0bf0000"));
							imgAdapter.setLiked(currentPos, true);
							Util.setLikeCount(imgData.get(currentPos)
									.getFeedID(), tvLikes, likeCount);
						}

					});
		} else {
			FbUtil.unLikeId(imgData.get(currentPos).getFeedID(), getActivity(),
					new AsyncHttpResponseHandler() {

						@Override
						public void onSuccess(int arg0, String response) {
							super.onSuccess(arg0, response);
							layoutLike.setBackgroundColor(Color
									.parseColor("#a0000000"));
							imgAdapter.setLiked(currentPos, false);
							Util.setLikeCount(imgData.get(currentPos)
									.getFeedID(), tvLikes, likeCount);
						}

					});
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);

	}

	@Override
	public void onClick(View v) {
		if (visible == false) {
			controlsView.setVisibility(View.GONE);
			// description.setVisibility(View.GONE);
			bar.setVisibility(View.GONE);
			visible = true;
		} else if (visible == true) {
			controlsView.setVisibility(View.VISIBLE);
			// description.setVisibility(View.VISIBLE);
			bar.setVisibility(View.VISIBLE);
			visible = false;
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		ImageLoader imageLoader = new ImageLoader(getApplicationContext());
		imageLoader.clearMemoryCache();
	}

}